package com.liuche.pictureserver.web.filter;

import com.liuche.pictureserver.pojo.domain.UserDO;
import com.liuche.pictureserver.pojo.dto.UserHolderDTO;
import com.liuche.pictureserver.service.IUserService;
import com.liuche.pictureserver.utils.BeanUtil;
import com.liuche.pictureserver.utils.UserHolder;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 接口请求过滤器
 *
 * @author liuche
 */
@Slf4j
@WebFilter(urlPatterns = "/*") // 指定过滤的URL模式
@Component
public class ApiRequestFilter extends OncePerRequestFilter {
    @Resource
    private IUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        UserDO curUser = null;
        try {
            curUser = userService.getCurUser(request);
        } catch (Exception e) {
            log.info("用户未登录");
        }
        // 保存用户信息
        if (!ObjectUtils.isEmpty(curUser)) {
            UserHolderDTO holder = BeanUtil.toBean(curUser, UserHolderDTO.class);
            UserHolder.saveUser(holder);
        }

        log.info("请求接口：{}", request.getRequestURI());
        filterChain.doFilter(request, response);
        log.info("结束啦！：{}", request.getRequestURI());
        UserHolder.removeUser();
    }
}
